// 日记服务 - 处理日记的CRUD操作和与后端API的交互

class DiaryService {
  constructor() {
    this.apiBaseUrl = '/api'; // 后端API基础路径
  }

  // 通用请求方法，带认证
  async request(endpoint, options = {}) {
    const url = `${this.apiBaseUrl}${endpoint}`;
    const token = localStorage.getItem('token');
    
    const defaultOptions = {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : '',
      },
    };

    const mergedOptions = {
      ...defaultOptions,
      ...options,
      headers: {
        ...defaultOptions.headers,
        ...options.headers,
      },
    };

    try {
      const response = await fetch(url, mergedOptions);
      
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || errorData.msg || `HTTP错误! 状态: ${response.status}`);
      }
      
      return await response.json();
    } catch (error) {
      console.error('日记API请求失败:', error);
      throw error;
    }
  }

  // 创建新日记
  async createDiary(diaryData) {
    const response = await this.request('/diary', {
      method: 'POST',
      body: JSON.stringify(diaryData),
    });
    
    // 根据后端返回格式调整
    return response.data || response;
  }

  // 获取日记列表
  async getDiaryList(params = {}) {
    // 构建查询参数
    const queryParams = new URLSearchParams();
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined && params[key] !== null) {
        queryParams.append(key, params[key]);
      }
    });
    
    const response = await this.request(`/diary?${queryParams.toString()}`);
    
    // 根据后端返回格式调整
    return response.data || response;
  }

  // 获取日记详情
  async getDiaryDetail(id) {
    const response = await this.request(`/diary/${id}`);
    
    // 根据后端返回格式调整
    return response.data || response;
  }

  // 更新日记
  async updateDiary(id, diaryData) {
    const response = await this.request(`/diary/${id}`, {
      method: 'PUT',
      body: JSON.stringify(diaryData),
    });
    
    // 根据后端返回格式调整
    return response.data || response;
  }

  // 删除日记
  async deleteDiary(id) {
    const response = await this.request(`/diary/${id}`, {
      method: 'DELETE',
    });
    
    // 根据后端返回格式调整
    return response.data || response;
  }

  // 获取日记统计信息
  async getDiaryStats() {
    const response = await this.request('/diary/stats/summary');
    
    // 根据后端返回格式调整
    return response.data || response;
  }

  // 格式化日期显示
  formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }

  // 获取情绪对应的图标
  getEmotionIcon(emotion) {
    const emotionIcons = {
      happy: '😊',
      excited: '🤗',
      calm: '😌',
      sad: '😢',
      anxious: '😰',
      angry: '😠',
      confused: '😕',
      tired: '😴',
      grateful: '🙏',
      loved: '💕'
    };
    return emotionIcons[emotion] || '😐';
  }

  // 获取情绪对应的标签
  getEmotionLabel(emotion) {
    const emotionLabels = {
      happy: '开心',
      excited: '兴奋',
      calm: '平静',
      sad: '难过',
      anxious: '焦虑',
      angry: '生气',
      confused: '困惑',
      tired: '疲惫',
      grateful: '感恩',
      loved: '被爱'
    };
    return emotionLabels[emotion] || '其他';
  }
}

// 导出单例实例
const diaryService = new DiaryService();
export default diaryService;